package com.sc.nft.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.sc.nft.dao.*;
import com.sc.nft.dto.DelSettlementRewardsDTO;
import com.sc.nft.entity.*;
import com.sc.nft.enums.*;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.*;
import com.sc.nft.sup.ErrorCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * 商户质押任务奖励结算日志表服务接口实现
 *
 * @author Sun
 * @since 2023-08-21 15:30:06
 * @description 由 Mybatisplus Code Generator 创建
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class MerchantPledgeTaskSettlementRewardsLogServiceImpl implements MerchantPledgeTaskSettlementRewardsLogService {

    private final MerchantPledgeTaskSettlementRewardsLogDao merchantPledgeTaskSettlementRewardsLogDao;
    private final UserMerchantPledgeTaskRecordsDao userMerchantPledgeTaskRecordsDao;
    private final MerchantPledgeTaskCycleConfDao merchantPledgeTaskCycleConfDao;
    private final MerchantPledgeTaskIncomeConfDao merchantPledgeTaskIncomeConfDao;
    private final MerchantPledgeTaskConfDao merchantPledgeTaskConfDao;
    private final MerchantPledgeTaskRewardsConfDao merchantPledgeTaskRewardsConfDao;
    private final UserInfoDao userInfoDao;
    private final EquityPropsDao equityPropsDao;
    private final UserEquityPropsService userEquityPropsService;
    private final UserRelevanceDao userRelevanceDao;
    private final UserMerchantPledgeTaskCollectionRecordsDao userMerchantPledgeTaskCollectionRecordsDao;
    private final UserCollectionService userCollectionService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void maintenancePledgeStatus(UserMerchantPledgeTaskRecords userMerchantPledgeTaskRecords) {
        //修改为质押中
        Assert.isTrue(userMerchantPledgeTaskRecordsDao.updateStatusById(userMerchantPledgeTaskRecords.getId(), UserMerchantPledgeTaskStatusEnum.IN_PLEDGE),()->new GlobalRunTimeException("更新失败"));
        //初始化结算周期到 sc_merchant_pledge_task_settlement_rewards_log

        List<MerchantPledgeTaskIncomeConf> incomeConfList = merchantPledgeTaskIncomeConfDao.getListByTaskId(userMerchantPledgeTaskRecords.getMerchantPledgeTaskId());
        //周期
        MerchantPledgeTaskCycleConf cycleConf = merchantPledgeTaskCycleConfDao.getById(userMerchantPledgeTaskRecords.getMerchantPledgeTaskCycleConfId());
        //获取活动配置
        MerchantPledgeTaskConf merchantPledgeTaskConf = merchantPledgeTaskConfDao.getById(userMerchantPledgeTaskRecords.getMerchantPledgeTaskId());
        //奖励次数
        int count = cycleConf.getPledgeCycle() / cycleConf.getRewardsCycle();

        Date now = new Date();
        now.setHours(10);
        now.setMinutes(0);
        now.setSeconds(0);

        for (MerchantPledgeTaskIncomeConf merchantPledgeTaskIncomeConf : incomeConfList) {
            //计算直推间推收益
            //规则: 1.上级和用户质押了同一个活动(直推)
            //      2.插入直推奖励 10点结算

            //手动质押当天发放，系统质押超出可退出时间在发放。
            Date IncomeTime = now;
            if(userMerchantPledgeTaskRecords.getIsAuto()){
                IncomeTime = DateUtil.offsetDay(now, cycleConf.getExitDay());
            }
            IncomeTime.setHours(10);
            IncomeTime.setMinutes(0);
            IncomeTime.setSeconds(0);

            if(merchantPledgeTaskIncomeConf.getPledgeIncomeType() == MerchantPledgeTaskIncomeTypeEnum.DIRECT_REVENUE){
                UserInfo user = userInfoDao.getById(userMerchantPledgeTaskRecords.getUserId());
                if(ObjectUtil.isNotNull(user.getRecommendUserId()) || user.getRecommendUserId() != 0){
                    UserInfo recommendUser = userInfoDao.getById(user.getRecommendUserId());
                    if(ObjectUtil.isNotNull(recommendUser)){
                        Integer recommendUserCount = userMerchantPledgeTaskRecordsDao.getSumPledgeCountByUserIdAndMerchantPledgeTaskId(recommendUser.getId(),userMerchantPledgeTaskRecords.getMerchantPledgeTaskId());
                        //判断上级是否质押了同一个活动,并且数量大于等于配置数量
                        if(recommendUserCount >= merchantPledgeTaskIncomeConf.getPledgeIncomeCondition()){
                            //插入直推奖励 10点结算
                            MerchantPledgeTaskSettlementRewardsLog merchantPledgeTaskSettlementRewardsLog = new MerchantPledgeTaskSettlementRewardsLog();
                            merchantPledgeTaskSettlementRewardsLog.setUserId(recommendUser.getId());
                            merchantPledgeTaskSettlementRewardsLog.setUserPledgeTaskRecordsId(userMerchantPledgeTaskRecords.getId());
                            merchantPledgeTaskSettlementRewardsLog.setMerchantPledgeTaskId(merchantPledgeTaskConf.getId());
                            merchantPledgeTaskSettlementRewardsLog.setMerchantPledgeTaskIncomeConfId(merchantPledgeTaskIncomeConf.getId());
                            merchantPledgeTaskSettlementRewardsLog.setRewardsType(MerchantPledgeTaskrewardsTypeEnum.DIRECT_REVENUE);
                            merchantPledgeTaskSettlementRewardsLog.setIsSettlement(Boolean.FALSE);
                            merchantPledgeTaskSettlementRewardsLog.setSettlementCount(userMerchantPledgeTaskRecords.getPledgeCount());
                            merchantPledgeTaskSettlementRewardsLog.setSettlementTime(IncomeTime);
                            merchantPledgeTaskSettlementRewardsLog.setFromUserId(user.getId());
                            merchantPledgeTaskSettlementRewardsLog.setFromUserRecordsId(userMerchantPledgeTaskRecords.getId());
                            merchantPledgeTaskSettlementRewardsLog.insert();
                        }
                    }
                }
            }else if(merchantPledgeTaskIncomeConf.getPledgeIncomeType() == MerchantPledgeTaskIncomeTypeEnum.EXTRAPOLATED_RETURN){
                UserInfo user = userInfoDao.getById(userMerchantPledgeTaskRecords.getUserId());
                //上上级用户信息
                UserRelevance userRelevance = userRelevanceDao.getByRelevanceIdAndLv(user.getId(),2);
                //上上级为空就结束
                if(ObjectUtil.isNull(userRelevance)){
                    continue;
                }

                //获取 上上级用户的直推用户
                List<UserRelevance> relevanceList = userRelevanceDao.getByUserIdAndLv(userRelevance.getUserId(), 1);
                if(relevanceList.size() == 0){
                    continue;
                }
                //获取间推的id集合
                List<Long> ids = relevanceList.stream().map(UserRelevance::getRelevanceId).collect(Collectors.toList());
                //查询当前用户的上上级质押数量(份数)
                Integer recommendUserCount = userMerchantPledgeTaskRecordsDao.getSumPledgeCountByUserIdAndMerchantPledgeTaskId(userRelevance.getUserId(),userMerchantPledgeTaskRecords.getMerchantPledgeTaskId());
                //查询间推集合的质押数量(份数)
                Integer  juniorCount = userMerchantPledgeTaskRecordsDao.getCountByJuniorIdsAndMerchantPledgeTaskId(ids,userMerchantPledgeTaskRecords.getMerchantPledgeTaskId());

                //判断上级是否质押了同一个活动,并且数量大于等于配置数量
                if(recommendUserCount >=1 && juniorCount >= merchantPledgeTaskIncomeConf.getPledgeIncomeCondition()){
                    //插入直推奖励 10点结算
                    MerchantPledgeTaskSettlementRewardsLog merchantPledgeTaskSettlementRewardsLog = new MerchantPledgeTaskSettlementRewardsLog();
                    merchantPledgeTaskSettlementRewardsLog.setUserId(userRelevance.getUserId());
                    //记录id 是来源用户的记录id
                    merchantPledgeTaskSettlementRewardsLog.setUserPledgeTaskRecordsId(userMerchantPledgeTaskRecords.getId());
                    merchantPledgeTaskSettlementRewardsLog.setMerchantPledgeTaskId(merchantPledgeTaskConf.getId());
                    merchantPledgeTaskSettlementRewardsLog.setMerchantPledgeTaskIncomeConfId(merchantPledgeTaskIncomeConf.getId());
                    merchantPledgeTaskSettlementRewardsLog.setRewardsType(MerchantPledgeTaskrewardsTypeEnum.EXTRAPOLATED_RETURN);
                    merchantPledgeTaskSettlementRewardsLog.setIsSettlement(Boolean.FALSE);
                    merchantPledgeTaskSettlementRewardsLog.setSettlementCount(userMerchantPledgeTaskRecords.getPledgeCount());
                    merchantPledgeTaskSettlementRewardsLog.setSettlementTime(IncomeTime);
                    merchantPledgeTaskSettlementRewardsLog.setFromUserId(user.getId());
                    merchantPledgeTaskSettlementRewardsLog.setFromUserRecordsId(userMerchantPledgeTaskRecords.getId());
                    merchantPledgeTaskSettlementRewardsLog.insert();
                }
            }
        }

        //最终时间
        DateTime endTime= DateUtil.offsetDay(now, cycleConf.getPledgeCycle());

        Date settlementTime = now;
        //周期收益
        for (int i = 0; i < count; i++) {
            //每次结算的时间
             settlementTime = DateUtil.offsetDay(settlementTime, cycleConf.getRewardsCycle());

            //结算记录
            MerchantPledgeTaskSettlementRewardsLog merchantPledgeTaskSettlementRewardsLog = new MerchantPledgeTaskSettlementRewardsLog();
            merchantPledgeTaskSettlementRewardsLog.setUserId(userMerchantPledgeTaskRecords.getUserId());
            merchantPledgeTaskSettlementRewardsLog.setUserPledgeTaskRecordsId(userMerchantPledgeTaskRecords.getId());
            merchantPledgeTaskSettlementRewardsLog.setMerchantPledgeTaskId(merchantPledgeTaskConf.getId());
            merchantPledgeTaskSettlementRewardsLog.setMerchantPledgeTaskCycleConfId(cycleConf.getId());
            merchantPledgeTaskSettlementRewardsLog.setRewardsType(MerchantPledgeTaskrewardsTypeEnum.PERIODIC_REWARD);
            merchantPledgeTaskSettlementRewardsLog.setIsSettlement(Boolean.FALSE);
            merchantPledgeTaskSettlementRewardsLog.setSettlementCount(userMerchantPledgeTaskRecords.getPledgeCount());
            merchantPledgeTaskSettlementRewardsLog.setSettlementTime(settlementTime);
            merchantPledgeTaskSettlementRewardsLog.insert();

            if(settlementTime.after(endTime)){
                break;
            }
        }
    }

    @Override
    public List<MerchantPledgeTaskSettlementRewardsLog> getPledgeTaskSettlementRewards() {
        return merchantPledgeTaskSettlementRewardsLogDao.getPledgeTaskSettlementRewards();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pledgeTaskSettlementRewards(MerchantPledgeTaskSettlementRewardsLog merchantPledgeTaskSettlementRewardsLog) {
        UserInfo user = userInfoDao.getById(merchantPledgeTaskSettlementRewardsLog.getUserId());
        MerchantPledgeTaskConf merchantPledgeTaskConf = merchantPledgeTaskConfDao.getById(merchantPledgeTaskSettlementRewardsLog.getMerchantPledgeTaskId());



        if(merchantPledgeTaskSettlementRewardsLog.getRewardsType() == MerchantPledgeTaskrewardsTypeEnum.PERIODIC_REWARD){//周期(每日奖励)
            //用户记录
            UserMerchantPledgeTaskRecords userReocrds = userMerchantPledgeTaskRecordsDao.getById(merchantPledgeTaskSettlementRewardsLog.getUserPledgeTaskRecordsId());
            if(ObjectUtil.isNull(userReocrds) || userReocrds.getIsFrozen()){
                Assert.isTrue(merchantPledgeTaskSettlementRewardsLogDao.deleteById(merchantPledgeTaskSettlementRewardsLog.getId()),()->new GlobalRunTimeException("删除失败"));
                return;
            }
            //周期配置
            MerchantPledgeTaskCycleConf cycleConf = merchantPledgeTaskCycleConfDao.getById(userReocrds.getMerchantPledgeTaskCycleConfId());
            //周期关联的奖励配置
            List<MerchantPledgeTaskRewardsConf> rewardsConfList = merchantPledgeTaskRewardsConfDao.getListByCycleConfId(cycleConf.getId());
            //发放奖励
            for (MerchantPledgeTaskRewardsConf merchantPledgeTaskRewardsConf : rewardsConfList) {
                //发奖励
                settlementRewards(merchantPledgeTaskRewardsConf,user,merchantPledgeTaskConf,merchantPledgeTaskSettlementRewardsLog.getSettlementCount());
                UserMerchantPledgeTaskDetailsRecords userMerchantPledgeTaskDetailsRecords = new UserMerchantPledgeTaskDetailsRecords();
                userMerchantPledgeTaskDetailsRecords.setUserPledgeTaskRecordsId(userReocrds.getId());
                userMerchantPledgeTaskDetailsRecords.setUserId(user.getId());
                userMerchantPledgeTaskDetailsRecords.setMerchantPledgeTaskId(merchantPledgeTaskConf.getId());
                userMerchantPledgeTaskDetailsRecords.setMerchantPledgeTaskCycleConfId(cycleConf.getId());
                userMerchantPledgeTaskDetailsRecords.setRewardsType(merchantPledgeTaskRewardsConf.getRewardsType());
                userMerchantPledgeTaskDetailsRecords.setLinkType(merchantPledgeTaskRewardsConf.getLinkType());
                userMerchantPledgeTaskDetailsRecords.setLinkName(merchantPledgeTaskRewardsConf.getLinkName());
                userMerchantPledgeTaskDetailsRecords.setLinkCount(merchantPledgeTaskRewardsConf.getLinkCount() *  merchantPledgeTaskSettlementRewardsLog.getSettlementCount());
                userMerchantPledgeTaskDetailsRecords.setLinkImg(merchantPledgeTaskRewardsConf.getLinkImg());
                userMerchantPledgeTaskDetailsRecords.setLinkId(merchantPledgeTaskRewardsConf.getLinkId());
                userMerchantPledgeTaskDetailsRecords.setSettlementRewardsLogId(merchantPledgeTaskSettlementRewardsLog.getId());
                userMerchantPledgeTaskDetailsRecords.insert();
            }
            Assert.isTrue(userMerchantPledgeTaskRecordsDao.addRewardsCountById(userReocrds.getId()),()->new GlobalRunTimeException("更新失败"));

        }else{

            if(merchantPledgeTaskSettlementRewardsLog.getRewardsType() == MerchantPledgeTaskrewardsTypeEnum.DIRECT_REVENUE){

                settlementRecommendedRewards(merchantPledgeTaskConf,MerchantPledgeTaskIncomeTypeEnum.DIRECT_REVENUE,user,merchantPledgeTaskSettlementRewardsLog,MerchantPledgeTaskrewardsTypeEnum.DIRECT_REVENUE);

            }else if(merchantPledgeTaskSettlementRewardsLog.getRewardsType() == MerchantPledgeTaskrewardsTypeEnum.EXTRAPOLATED_RETURN){

                settlementRecommendedRewards(merchantPledgeTaskConf,MerchantPledgeTaskIncomeTypeEnum.EXTRAPOLATED_RETURN,user,merchantPledgeTaskSettlementRewardsLog,MerchantPledgeTaskrewardsTypeEnum.EXTRAPOLATED_RETURN);
            }

        }
        MerchantPledgeTaskSettlementRewardsLog byId = merchantPledgeTaskSettlementRewardsLogDao.getById(merchantPledgeTaskSettlementRewardsLog.getId());
        if(ObjectUtil.isNotNull(byId)){
            //修改为已结算
            Assert.isTrue(merchantPledgeTaskSettlementRewardsLogDao.updateIsSettlementById(Boolean.TRUE,merchantPledgeTaskSettlementRewardsLog.getId()),()->new GlobalRunTimeException("更新失败"));
        }
    }


    @Override
    public List<UserMerchantPledgeTaskRecords> getExpireList() {
        return userMerchantPledgeTaskRecordsDao.getExpireList(UserMerchantPledgeTaskStatusEnum.IN_PLEDGE);
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void autoUserMerchantPledgeTaskRecords(UserMerchantPledgeTaskRecords oldRecords) {
        // 5.7.0 修改为 到期自动结束 所有DAO都是 释放质押藏品
        //获取用户质押藏品
        List<UserMerchantPledgeTaskCollectionRecords> listByUserRecordsId = userMerchantPledgeTaskCollectionRecordsDao.getListByUserRecordsId(oldRecords.getId());
        List<Long> userCollectionIds = listByUserRecordsId.stream().map(UserMerchantPledgeTaskCollectionRecords::getUserCollectionId).collect(Collectors.toList());
        //批量释放用户藏品
        userCollectionService.updateFreezingStatusByIds(userCollectionIds,UserCollectionFreezingStatusEnum.NORMAL);
        //修改状态
        userMerchantPledgeTaskRecordsDao.updateStatusById(oldRecords.getId(),UserMerchantPledgeTaskStatusEnum.ALREADY_ENDED);


//        Long daoId = oldRecords.getDaoId();
//        //Arrays.asList(20L,21L).contains(oldRecords.getMerchantPledgeTaskId())
//        if(daoId.intValue() != 15){//dao是不是马小优的
//            //1.如果不是马小优的  则判断质押数量是否大于配置的质押上限
//            //2.如果不大于 则继续质押
//            //3.如果大于  则自动退出
//
//            //获取活动配置
//            MerchantPledgeTaskConf merchantPledgeTaskConf = merchantPledgeTaskConfDao.getById(oldRecords.getMerchantPledgeTaskId());
//            //获取用户质押数量
//            Integer merchantPledgeCount = userMerchantPledgeTaskRecordsDao.getCountMerchantPledgeTaskId(oldRecords.getMerchantPledgeTaskId());
//            //如果质押数量 大于等于 上限 则自动退出  或者 当前时间大于结束时间
//            if(merchantPledgeCount.intValue() >= merchantPledgeTaskConf.getUpperLimit() || DateTime.now().isAfter(oldRecords.getExitTime())){
//                //获取用户质押藏品
//                List<UserMerchantPledgeTaskCollectionRecords> listByUserRecordsId = userMerchantPledgeTaskCollectionRecordsDao.getListByUserRecordsId(oldRecords.getId());
//                List<Long> userCollectionIds = listByUserRecordsId.stream().map(UserMerchantPledgeTaskCollectionRecords::getUserCollectionId).collect(Collectors.toList());
//                //批量释放用户藏品
//                Assert.isTrue(userCollectionService.updateFreezingStatusByIds(userCollectionIds,UserCollectionFreezingStatusEnum.NORMAL),()->new GlobalRunTimeException(StrUtil.format("藏品释放失败,记录id:{}",oldRecords.getId())));
//                //修改状态
//                Assert.isTrue(userMerchantPledgeTaskRecordsDao.updateStatusById(oldRecords.getId(),UserMerchantPledgeTaskStatusEnum.ALREADY_ENDED),()->new GlobalRunTimeException(StrUtil.format("退出失败,记录id:{}",oldRecords.getId())));
////                Assert.isTrue(merchantPledgeTaskSettlementRewardsLogDao.delByUserIdAndUserPledgeTaskRecordsId(oldRecords.getUserId(),oldRecords.getId()),()->new GlobalRunTimeException(StrUtil.format("退出失败,记录id:{}",oldRecords.getId())));
////                merchantPledgeTaskSettlementRewardsLogDao.delIncomeRecordsByUserIdAndUserPledgeTaskRecordsId(oldRecords.getUserId(),oldRecords.getId());
//                return;
//            }
//
//        }
//        //修改为已完成
//        Assert.isTrue(userMerchantPledgeTaskRecordsDao.updateStatusById(oldRecords.getId(),UserMerchantPledgeTaskStatusEnum.COMPLETED),()->new GlobalRunTimeException("更新失败"));
//        UserMerchantPledgeTaskRecords autoRecords = BeanUtil.copyProperties(oldRecords, UserMerchantPledgeTaskRecords.class);
//        DateTime now = DateTime.now();
//
//        MerchantPledgeTaskCycleConf cycleConf = merchantPledgeTaskCycleConfDao.getById(oldRecords.getMerchantPledgeTaskCycleConfId());
//
//        DateTime endTime = DateUtil.offset(now, DateField.HOUR, (cycleConf.getPledgeCycle() + 1) * 24);
//        endTime.setHours(0);
//        endTime.setMinutes(0);
//        endTime.setSeconds(0);
//        autoRecords.setEndTime(endTime);
//
//
//        DateTime exitTime = DateUtil.offset(now, DateField.HOUR, (cycleConf.getExitDay() + 1)* 24);
//        exitTime.setHours(0);
//        exitTime.setMinutes(0);
//        exitTime.setSeconds(0);
//        autoRecords.setExitTime(exitTime);
//
//        List<MerchantPledgeTaskRewardsConf> cycleRewardsLst = merchantPledgeTaskRewardsConfDao.getListByCycleConfId(cycleConf.getId());
//        String rewardsDetails = cycleRewardsLst.stream()
//                .map(conf -> conf.getLinkName() + "*" + conf.getLinkCount())
//                .collect(Collectors.joining(","));
//
//        autoRecords.setRewardsDetails(rewardsDetails);
//        autoRecords.setIsAuto(Boolean.TRUE);
//        autoRecords.setStatus(UserMerchantPledgeTaskStatusEnum.NOT_YET_STARTED);
//        autoRecords.setRewardsCount(0);
//        autoRecords.setSettleDay(0);
//        autoRecords.insert();
//
//        List<UserMerchantPledgeTaskCollectionRecords> listByUserRecordsId = userMerchantPledgeTaskCollectionRecordsDao.getListByUserRecordsId(oldRecords.getId());
//        for (UserMerchantPledgeTaskCollectionRecords userMerchantPledgeTaskCollectionRecords : listByUserRecordsId) {
//            UserMerchantPledgeTaskCollectionRecords autoPledgeTaskCollection = new UserMerchantPledgeTaskCollectionRecords();
//            autoPledgeTaskCollection.setUserId(userMerchantPledgeTaskCollectionRecords.getUserId());
//            autoPledgeTaskCollection.setUserRecordsId(autoRecords.getId());
//            autoPledgeTaskCollection.setUserCollectionId(userMerchantPledgeTaskCollectionRecords.getUserCollectionId());
//            autoPledgeTaskCollection.setCollectionId(userMerchantPledgeTaskCollectionRecords.getCollectionId());
//            autoPledgeTaskCollection.setCollectionName(userMerchantPledgeTaskCollectionRecords.getCollectionName());
//            autoPledgeTaskCollection.setCollectionImage(userMerchantPledgeTaskCollectionRecords.getCollectionImage());
//            autoPledgeTaskCollection.setNumbering(userMerchantPledgeTaskCollectionRecords.getNumbering());
//            autoPledgeTaskCollection.insert();
//        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DelSettlementRewardsDTO delSettlementRewardsByUserRecordsId(Long id) {
        log.info("商户后台强制退出用户记录:{}",id);
        UserMerchantPledgeTaskRecords userMerchantPledgeTaskRecords = userMerchantPledgeTaskRecordsDao.getById(id);
        Assert.notNull(userMerchantPledgeTaskRecords,()->new GlobalRunTimeException("记录不存在"));
        DelSettlementRewardsDTO delSettlementRewardsDTO = new DelSettlementRewardsDTO();
        if(userMerchantPledgeTaskRecords.getStatus() == UserMerchantPledgeTaskStatusEnum.IN_PLEDGE){

            //删除待结算周期记录
            Assert.isTrue(merchantPledgeTaskSettlementRewardsLogDao.delByUserPledgeTaskRecordsId(id),()->new GlobalRunTimeException("删除失败"));
            //删除待结算的收益记录
            merchantPledgeTaskSettlementRewardsLogDao.delIncomeRecordsByUserPledgeTaskRecordsId(id);
        }

        //释放藏品
        //获取用户质押藏品
        List<UserMerchantPledgeTaskCollectionRecords> listByUserRecordsId = userMerchantPledgeTaskCollectionRecordsDao.getListByUserRecordsId(id);
        List<Long> userCollectionIds = listByUserRecordsId.stream().map(UserMerchantPledgeTaskCollectionRecords::getUserCollectionId).collect(Collectors.toList());
        log.info("商户后台强制退出用户藏品质押id:{}",userCollectionIds);
        log.info("商户后台强制退出用户藏品质押id:{}",userCollectionIds);
        log.info("商户后台强制退出用户藏品质押id:{}",userCollectionIds);
        //批量释放用户藏品
        Assert.isTrue(userCollectionService.updateFreezingStatusByIds(userCollectionIds,UserCollectionFreezingStatusEnum.NORMAL),()->new GlobalRunTimeException("藏品释放失败,请稍后重试"));

        delSettlementRewardsDTO.setResult(Boolean.TRUE);
        return delSettlementRewardsDTO;
    }

    private void settlementRewards(MerchantPledgeTaskRewardsConf merchantPledgeTaskRewardsConf,UserInfo user,MerchantPledgeTaskConf merchantPledgeTaskConf,int count){
        if(merchantPledgeTaskRewardsConf.getLinkType() == MerchantPledgeTaskLinkTypeEnum.PROPS){//权益道具
            //添加到用户账户
            EquityProps equityProps = equityPropsDao.getById(merchantPledgeTaskRewardsConf.getLinkId());
            Assert.notNull(equityProps,()->new GlobalRunTimeException(ErrorCode.EQUITY_PROPS_DO_NOT_EXIST));
            userEquityPropsService.addEquityPropsByUser(equityProps,user.getId(), UserEquityPropsGetTypeEnum.MERCHANT_PLEDGE_TASK, merchantPledgeTaskRewardsConf.getLinkCount() * count,merchantPledgeTaskConf.getPledgeName(),merchantPledgeTaskConf.getId(), BigDecimal.ZERO,UserEquityPropsGetTypeEnum.MERCHANT_PLEDGE_TASK,merchantPledgeTaskConf.getId());
        }
    }


    private void settlementRecommendedRewards(MerchantPledgeTaskConf merchantPledgeTaskConf,MerchantPledgeTaskIncomeTypeEnum incomeTypeEnum,UserInfo user,MerchantPledgeTaskSettlementRewardsLog merchantPledgeTaskSettlementRewardsLog,MerchantPledgeTaskrewardsTypeEnum rewardsTypeEnum){
        UserMerchantPledgeTaskRecords formUserRecords = userMerchantPledgeTaskRecordsDao.getById(merchantPledgeTaskSettlementRewardsLog.getFromUserRecordsId());
        if(ObjectUtil.isNull(formUserRecords) || formUserRecords.getStatus() != UserMerchantPledgeTaskStatusEnum.IN_PLEDGE){
            return;
        }
//        if(formUserRecords.getIsFrozen() == Boolean.TRUE){
//            merchantPledgeTaskSettlementRewardsLogDao.deleteById(merchantPledgeTaskSettlementRewardsLog.getId());
//            return;
//        }


        Integer count = userMerchantPledgeTaskRecordsDao.getSumPledgeCountByUserIdAndMerchantPledgeTaskId(merchantPledgeTaskSettlementRewardsLog.getUserId(), merchantPledgeTaskConf.getId());
        if(count == 0){
            merchantPledgeTaskSettlementRewardsLogDao.deleteById(merchantPledgeTaskSettlementRewardsLog.getId());
            return;
        }

        //直推收益
        MerchantPledgeTaskIncomeConf merchantPledgeTaskIncomeConf = merchantPledgeTaskIncomeConfDao.getListByTaskIdAndType(merchantPledgeTaskConf.getId(), incomeTypeEnum);
        //直推收益对应奖励
        List<MerchantPledgeTaskRewardsConf> incomeRewardsConf = merchantPledgeTaskRewardsConfDao.getListByIncomeConfId(merchantPledgeTaskIncomeConf.getId());
        //奖励累计

        UserMerchantPledgeTaskIncomeRecords userMerchantPledgeTaskIncomeRecords = new UserMerchantPledgeTaskIncomeRecords();
        userMerchantPledgeTaskIncomeRecords.setDaoId(merchantPledgeTaskConf.getDaoId());
        userMerchantPledgeTaskIncomeRecords.setDaoName(merchantPledgeTaskConf.getDaoName());
        userMerchantPledgeTaskIncomeRecords.setUserId(user.getId());
        userMerchantPledgeTaskIncomeRecords.setMerchantPledgeTaskId(merchantPledgeTaskConf.getId());
        userMerchantPledgeTaskIncomeRecords.setPledgeIncomeType(incomeTypeEnum);


        userMerchantPledgeTaskIncomeRecords.setFromUserId(formUserRecords.getUserId());

        userMerchantPledgeTaskIncomeRecords.setFromUserPledgeTaskRecordsId(merchantPledgeTaskSettlementRewardsLog.getUserPledgeTaskRecordsId());
        userMerchantPledgeTaskIncomeRecords.setRewardsCount(formUserRecords.getPledgeCount());

        String rewardsDetails = incomeRewardsConf.stream()
                .map(conf -> conf.getLinkName() + "*" + conf.getLinkCount())
                .collect(Collectors.joining(","));
        userMerchantPledgeTaskIncomeRecords.setRewardsDetails(rewardsDetails);

        userMerchantPledgeTaskIncomeRecords.setPledgeName(merchantPledgeTaskConf.getPledgeName());
        userMerchantPledgeTaskIncomeRecords.insert();


        for (MerchantPledgeTaskRewardsConf merchantPledgeTaskRewardsConf : incomeRewardsConf) {
            settlementRewards(merchantPledgeTaskRewardsConf,user,merchantPledgeTaskConf,merchantPledgeTaskSettlementRewardsLog.getSettlementCount());

            UserMerchantPledgeTaskDetailsRecords userMerchantPledgeTaskDetailsRecords = new UserMerchantPledgeTaskDetailsRecords();
            userMerchantPledgeTaskDetailsRecords.setUserPledgeTaskRecordsId(merchantPledgeTaskConf.getId());
            userMerchantPledgeTaskDetailsRecords.setUserPledgeTaskIcomeRecordsId(userMerchantPledgeTaskIncomeRecords.getId());
            userMerchantPledgeTaskDetailsRecords.setUserId(merchantPledgeTaskSettlementRewardsLog.getUserId());
            userMerchantPledgeTaskDetailsRecords.setMerchantPledgeTaskId(merchantPledgeTaskConf.getId());
            userMerchantPledgeTaskDetailsRecords.setMerchantPledgeTaskCycleConfId(0L);
            userMerchantPledgeTaskDetailsRecords.setRewardsType(rewardsTypeEnum);
            userMerchantPledgeTaskDetailsRecords.setLinkType(merchantPledgeTaskRewardsConf.getLinkType());
            userMerchantPledgeTaskDetailsRecords.setLinkName(merchantPledgeTaskRewardsConf.getLinkName());
            userMerchantPledgeTaskDetailsRecords.setLinkCount(merchantPledgeTaskRewardsConf.getLinkCount() * merchantPledgeTaskSettlementRewardsLog.getSettlementCount());
            userMerchantPledgeTaskDetailsRecords.setLinkImg(merchantPledgeTaskRewardsConf.getLinkImg());
            userMerchantPledgeTaskDetailsRecords.setLinkId(merchantPledgeTaskRewardsConf.getLinkId());
            userMerchantPledgeTaskDetailsRecords.setSettlementRewardsLogId(merchantPledgeTaskSettlementRewardsLog.getId());
            userMerchantPledgeTaskDetailsRecords.insert();
        }
    }
}